<template>
  <div id="incity">
    <div id="end-searcher" v-if="endMode">
      <div class="city-name">
        <div>{{currentCity}}</div>
      </div>
      <md-input-item @focus="onEndSearcherFocus" type="text" v-model="searchValue" class="searcher-input" ref="searcherInput" placeholder="您要去哪儿">
        <md-icon name="clear_icon" slot="right" v-show="searchValue!=''" @click="clearSearchValue"></md-icon>
      </md-input-item>
      <div class="searcher-btn" @click="onEndSearcherCancel">取消</div>
    </div>
    <div v-if="showEndPoiList" class="poi-list">
      <incity-poi-list
        :historyList="incityHistoryAddress"
        :searchList="searchList"
        @onItemSelect="onEndPoiListSelect"
        v-if="incityHistoryAddress.length>0||searchList.length>0"
      ></incity-poi-list>
      <div class="no-result" v-else>
        <md-icon class="icon" name="taxi_add_kst"></md-icon>
        <div class="text">暂无结果</div>
      </div>
    </div>
    <incity-map ref="map" :class="mapClass" @select="onMapSelect" @complete="onMapComplete" @dragstart="onMapDragStart"></incity-map>
    <div class="top_bar" v-if="topBar">
      <p>
        <md-icon class="back_btn" name="snyc_nav_fh" @click="goIncityBack()"></md-icon>
      </p>
    </div>
    <city-bottom
      v-show="!showEndPoiList"
      ref="bottom"
      :startLoading="startLoading"
      :endLoading="endLoading"
      :endOk="endOk"
      @selectStart="selectStart"
      @selectEnd="selectEnd"
      @ConfirmCallCarBtn="ConfirmCallCarBtn"
      @confirmEnd="confirmEnd"
      @dingweiBtn="onDingweiButtonClick"
    ></city-bottom>
  </div>
</template>

<script>
import '@/assets/svgs/snyc_nav_fh.svg';
import '@/assets/svgs/taxi_add_kst.svg';
import '@/assets/svgs/clear_icon.svg';
import IncityMap from './IncityMap';
import Popup from './popup';
import CityBottom from './components/CityBottom';
import { mapGetters } from 'vuex';
import { decryptByDESModeEBC, encryptByDESModeEBC } from '@/common/encrypt';
import PositionList from './popup/search/PositionList';
import Utils from '@/common/pakjUtils';
import { Dialog, InputItem, Icon, Toast } from 'mand-mobile';
import { GPS_UNKNOWN, GPS_LOCATING, GPS_SUCCESS, GPS_ERROR } from '@/store/gps.types';
import { GET_CURRENT_LOCATION } from '@/store/actions.types';
const GPS_ERROR_DIALOG_STATUS = 'gpsErrorDialogStatus';
export default {
  name: 'incity',
  components: {
    [IncityMap.name]: IncityMap,
    [CityBottom.name]: CityBottom,
    [InputItem.name]: InputItem,
    [PositionList.name]: PositionList,
    [Icon.name]: Icon
  },
  data() {
    return {
      topBar: false,
      endMode: false, // 是否为选择终点模式
      startLoading: false,
      startOk: false,
      startOkStatus: '',
      endLoading: false,
      endOk: false,
      mapClass: 'map',
      currentCity: '',
      searchValue: '',
      searchList: [],
      showEndPoiList: false,
      autoComplete: null,
      currentSelectedPoi: null,
      currentTempPoi: null,
      source: ''
    };
  },
  created() {
    if (this.$route.name === 'homeIncity') {
      this.mapClass = 'map';
    } else {
      this.mapClass = 'map100';
    }
    this.checkGpsStatus();
    // this.getIncityInfo();
  },
  methods: {
    clearSearchValue() {
      this.searchValue = '';
    },
    goIncityBack() {
      window.location.reload();
    },
    getIncityInfo() {
      return new Promise((resolve, reject) => {
        this.$store
          .dispatch('getIncityInfoByCoord', this.incityStartPosition.coordinate)
          .then(() => {
            this.startLoading = false;
            this.changeAutoCompleteOption(this.incityStartPosition.adcode);
            if (this.incityInfo) {
              console.log('市内用车：当前城市信息', this.incityInfo);
              if (this.incityHasTaxi) {
                // 判断当前城市是否有出租车服务,如果有出租车服务则不判断围栏范围
                this.$refs.map.createTextTip(this.incityStartPosition.coordinate, '在这里出发');
                this.startOk = true;
              } else {
                // 如果没有出租车服务需要判断当前位置是否超出围栏范围
                if (!this.endMode) {
                  if (this.$refs.map.isContain(this.incityStartPosition.coordinate)) {
                    this.$refs.map.createTextTip(this.incityStartPosition.coordinate, '在这里出发');
                    this.startOk = true;
                  } else {
                    this.$refs.map.createTextTip(this.incityStartPosition.coordinate, '该区域未开通服务，请在红色围栏内选择起点');
                  }
                }
              }
            } else {
              this.startLoading = false;
              this.startOk = false;
              let error = new Error('市内用车：当前城市未开通服务');
              reject(error);
              this.$refs.map.createTextTip(this.incityStartPosition.coordinate, '当前城市未开通市内用车服务');
            }
          })
          .catch(reason => {
            reject(reason);
            this.startLoading = false;
            this.startOk = false;
            let messageArr = reason.message.split(',');
            if (messageArr.length > 0) {
              if (messageArr[0] === '000001') {
                this.startOkStatus = 2;
                this.$refs.map.createTextTip(this.incityStartPosition.coordinate, messageArr[1]);
              } else if (messageArr[0] === '600001') {
                this.startOkStatus = 1;
                this.$refs.map.createTextTip(this.incityStartPosition.coordinate, messageArr[1]);
              }
            } else {
              this.$refs.map.createTextTip(this.incityStartPosition.coordinate, reason.message);
            }
          });
      });
    },
    init() {
      /**
       * 1.获取当前定位信息提交给服务器获取当前城市市内出行数据
       * 2.初始化地图、初始化拖拽选点、绘制围栏、展示附近车辆
       * 3.拖拽选点后把拖拽后的坐标发送给服务器判断是否出现城市变化，如果城市变化重新初始化城市数据
       * 4.选择好起点以及终点后把起点、终点数据提交给服务器获取可用什么方式进行约车，价格是多少
       * 5.用户选择好出行方式并确认约车后，进行支付流程
       * 6.支付流程用户可以选择优惠卷、支付方式
       * 7.用户支付完成则订单创建成功，进入等待派单界面，如果此时用户取消订单为无责取消
       * 8.司机抢单或者系统派单后直接进入接驾中界面，显示系统规划的路线信息
       * 9.司机到达用户上车点位置后提示司机已到达
       * 10.用户上车后进入行程中界面，行程中界面需要界面定期刷新，展示即将行走的路程以及已经行驶过的路程
       * 11.行程结束后进入匿名评价界面，用户选择星星进行评价，不同的星星会有不同的TAG提供用户进行选择
       */
      if (this.$refs.map) {
        if (this.incityStatus === 0) {
          this.$refs.map.clearMap();
          this.$refs.map.initCenter(this.getCurrentLocation.coordinate);
          this.$refs.map.initPositionPicker();
          if (this.incityInfo) {
            this.$refs.map.initFences(this.incityFence);
          }
        } else if (this.incityStatus === 1) {
          this.$refs.map.clearMap();
          this.$refs.map.stopPositionPicker();
          this.$refs.map.setFitView();
        } else if (this.incityStatus === 2) {
          console.log('市内用车：支付完成获取订单信息');
        }
      }
    },
    onMapComplete() {
      this.init();
    },
    onMapDragStart() {
      this.$refs.map.closeTextTip();
      this.currentSelectedPoi = null;
      if (!this.endMode) {
        this.startLoading = true;
        this.startOk = false;
      }
    },
    onMapSelect(poi) {
      if (poi.adsorption) {
        this.onMapSelect1(poi);
        return;
      }
      const coord = poi.coordinate.join(',');
      let params = {
        type: '2', // 1：城际；2：市内；3：顺风车
        lnglat: coord
      };
      this.$store.dispatch('getAdsorptionSiteByLnglat', params).then(res => {
        if (res.fence != undefined && res.fence != '') {
          this.$refs.map.createAdsorptionFence(res.fence);
          if (res.adsorption && res.adsorption instanceof Array) {
            if (res.adsorption.length >= 1) {
              this.$refs.map.createAdsorptionMarkers(res.adsorption);
            }
          }
        } else {
          this.onMapSelect1(poi);
          this.$refs.map.clearAdsorption();
        }
      });
    },
    onMapSelect1(poi) {
      this.currentTempPoi = poi;
      if (this.endMode) {
        this.endLoading = false;
        // if (this.incityStartPosition.adcode !== poi.adcode) {
        //     debugger;
        //     this.$refs.map.createTextTip(poi.coordinate, '请选择与起点相同的城市');
        //     return;
        // }
        let lnglatStr = poi.coordinate.join(',');
        let params = {
          lnglat: encryptByDESModeEBC(lnglatStr),
          cityId: this.incityInfo.cityId
        };
        this.$store
          .dispatch('checkInityEndPosition', params)
          .then(() => {
            if (this.currentSelectedPoi) {
              this.$store.commit('changeIncityEndPosition', this.currentSelectedPoi);
            } else {
              this.$store.commit('changeIncityEndPosition', poi);
            }
            this.$refs.map.createTextTip(poi.coordinate, '请选择终点');
            this.endOk = true;
          })
          .catch(reason => {
            this.$refs.map.createTextTip(poi.coordinate, reason.message);
            this.$store.commit('changeIncityEndPosition', poi);
            this.endOk = false;
          });
      } else {
        if (this.currentSelectedPoi) {
          this.$store.commit('changeIncityStartPosition', this.currentSelectedPoi);
        } else {
          this.$store.commit('changeIncityStartPosition', poi);
        }
        this.getIncityInfo();
      }
    },
    onEndPoiListSelect(poi) {
      this.searchList = [];
      poi.coordinate = poi.coordinate.split(',');
      this.currentSelectedPoi = poi;
      this.searchValue = '';
      this.showEndPoiList = false;
      this.$refs.map.setCenter(poi.coordinate);
      this.$store.dispatch('getIncityHistoryAddress', this.incityInfo.cityId);
    },
    selectStart() {
      Popup.selectStartPosition(this.startOk).then(position => {
        position.coordinate = position.coordinate.split(',');
        this.currentSelectedPoi = position;
        this.$refs.map.setCenter(position.coordinate);
      });
    },
    selectEnd() {
      if (this.startLoading) {
        Toast({
          content: '请选择起点',
          position: 'bottom',
          icon: 'circle-alert',
          duration: 1000
        });
        return;
      }
      if (!this.startOk) {
        var text = '';
        if (this.startOkStatus === 1) {
          text = '请在红色围栏内选择起点';
        } else {
          text = '当前城市暂未开通，请在起点切换已开通城市';
        }
        Toast({
          content: text,
          position: 'bottom',
          icon: 'circle-alert',
          duration: 1000
        });
        return;
      }
      this.endModeOn();
      this.topBar = false;
    },
    confirmEnd() {
      let startLnglat = this.incityStartPosition.coordinate.join(',');
      let endLnglat = this.incityEndPosition.coordinate.join(',');
      let params = {
        cityId: this.incityInfo.cityId,
        startLnglat: encryptByDESModeEBC(startLnglat),
        endLnglat: encryptByDESModeEBC(endLnglat),
        orderNum: encryptByDESModeEBC(this.getIncityCarpoolingNumberData),
        redMoney: undefined
      };
      this.$store.dispatch('getIncityDoOrder', params).then(() => {
        this.topBar = true;
        console.log(this.incityDoOrderInfo); // 用车类型选择
        if (this.incityDoOrderInfo.length === 0) {
          Dialog.alert({
            title: '提示',
            content: '该区域未开通服务，请在红色围栏内选择终点',
            confirmText: '我知道了'
          });
        } else {
          this.$refs.map.clearMap();
          this.$refs.map.stopPositionPicker();
          this.$refs.map.showStartEndPosition(this.incityStartPosition, this.incityEndPosition);
          this.endMode = false;
          this.$store.commit('changeIncityStatus', 2);
        }
      });
    },
    // 确认叫车
    ConfirmCallCarBtn() {
      if (Utils.getCurrentEnv() === 'wx') {
        // 微信
        this.source = '4';
      } else if (Utils.getCurrentEnv() === 'mini') {
        // 小程序
        this.source = '5';
      } else if (Utils.getCurrentEnv() === 'h5') {
        // H5
        this.source = '6';
      }
      if (this.getIncityCarTypeData === '1' || this.getIncityCarTypeData === '2') {
        // 市内用车
        let params = {
          cityId: this.incityInfo.cityId, // 城市ID
          startPst: this.incityStartPosition.stationName, // 起点短地址
          startPstDetail: this.incityStartPosition.position, // 起点长地址
          startLnglat: encryptByDESModeEBC(this.incityStartPosition.coordinate.join(',')), // 起点经纬度(DES加密)
          endPst: this.incityEndPosition.stationName, // 终点短地址
          endPstDetail: this.incityEndPosition.position, // 终点长地址
          endLnglat: encryptByDESModeEBC(this.incityEndPosition.coordinate.join(',')), // 终点经纬度(DES加密)
          orderAmt: this.getIncityOrderMoneyData, // 订单金额(DES加密)
          orderNum: encryptByDESModeEBC(this.getIncityCarpoolingNumberData), // 拼车人数
          type: this.getIncityCarTypeData, // 订单类型(1:市内用车/2:市内专车)
          source: this.source
        };
        this.$store
          .dispatch('incityCallCar', params)
          .then(() => {
            // 订单支付页面
            this.$router.replace({
              name: 'IncityOrderPay',
              query: {
                orderNo: this.getIncityCallCarData.orderNo
              }
            });
          })
          .catch(error => {
            let str = error.toString().split(':');
            let code = str[1].trim();
            let msgText = str[2];
            if (code === '700002') {
              Dialog.confirm({
                title: '提示',
                content: '您本周订单免责取消次数已用完，已无法继续用车，下周一恢复用车服务',
                confirmText: '取消规则',
                cancelText: '确定',
                onConfirm: () => {
                  this.$router.replace({
                    name: 'IncityCancelRule'
                  });
                }
              });
            }
          });
      } else {
        // 出租车
        var taxiType = '';
        if (this.getIncityCarTypeData === '3') {
          // 出租车打表
          taxiType = '1';
        } else if (this.getIncityCarTypeData === '4') {
          // 出租车一口价
          taxiType = '2';
        }
        let params = {
          type: this.getTaxiTravelTypeData || '1', // 订单类型 1现在 2 预约
          start_pst: this.incityStartPosition.stationName, // 起点位置
          start_pst_detail: this.incityStartPosition.position, // 起点详细位置
          start_lnglat: encryptByDESModeEBC(this.incityStartPosition.coordinate.join(',')), // 起点经纬度
          end_pst: this.incityEndPosition.stationName, // 终点位置
          end_pst_detail: this.incityEndPosition.position, // 终点详细位置
          end_lnglat: encryptByDESModeEBC(this.incityEndPosition.coordinate.join(',')), // 终点经纬度
          reward_money: this.getIncityRedMoneyData, // 红包金额
          price_model: taxiType, // 计价方式 1 打表计价 2 一口价
          expect_date: this.getIncityTimeData, // 预约时间戳
          fixed_price: this.getIncityOrderMoneyData, // 一口价金额
          source: this.source
        };
        this.$store
          .dispatch('getCallTaxi', params)
          .then(() => {
            this.$router.replace({
              name: 'taxi',
              query: {
                orderno: this.getCallTaxiData.order_no
              }
            });
          })
          .catch(error => {
            let str = error.toString().split(':');
            let code = str[1].trim();
            let msgText = str[2];
            if (code === '250250') {
              Dialog.alert({
                title: '提示',
                content: '当前选择时间已超时，请重新选择预约时间后提交订单',
                confirmText: '确定'
              });
            }
          });
      }
    },
    toggleEndMode() {
      if (this.endMode) {
        this.endModeOff();
      } else {
        this.endModeOn();
      }
    },
    endModeOn() {
      this.hideTop();
      this.endLoading = true;
      this.$store.commit('changeIncityStatus', 1);
      this.endMode = true;
      AMap.plugin('AMap.Autocomplete', () => {
        let autoOptions = {
          city: this.incityStartPosition.adcode,
          citylimit: true
        };
        this.autoComplete = new AMap.Autocomplete(autoOptions);
      });
      this.$store.dispatch('getIncityHistoryAddress', this.incityInfo.cityId);
      if (this.incityFenceCenter) {
        this.$refs.map.setCenterAndFitview(this.incityFenceCenter);
      } else {
        this.onMapSelect(this.currentTempPoi);
      }
    },
    endModeOff() {
      this.showTop();
      this.$refs.map.setCenter(this.incityStartPosition.coordinate);
      this.$refs.map.createTextTip(this.incityStartPosition.coordinate, '在这里出发');
      this.$store.commit('changeIncityStatus', 0);
      // this.$refs.map.initCenter(this.getCurrentLocation.coordinate);
      this.$store.commit('changeIncityEndPosition', null);
      this.endMode = false;
      this.showEndPoiList = false;
    },
    hideTop() {
      this.$emit('hideTop');
      this.mapClass = 'map100';
    },
    showTop() {
      this.$emit('showTop');
      this.mapClass = 'map';
    },
    onEndSearcherFocus() {
      this.showEndPoiList = true;
    },
    onEndSearcherCancel() {
      this.endModeOff();
      this.searchValue = '';
      this.searchList = [];
      this.$store.commit('setIncityHistoryAdress', []); // 终点取消时候 清除历史记录
    },
    changeAutoCompleteOption(cityCode) {
      if (this.autoComplete) {
        this.autoComplete.setCity(cityCode);
        this.autoComplete.setCityLimit(true);
      }
    },
    checkGpsStatus() {
      switch (this.gpsStatus) {
        case GPS_SUCCESS:
          this.init();
          break;
        case GPS_ERROR:
          this.showGpsErrorDialog();
          break;
      }
    },
    showGpsErrorDialog() {
      let dialogStatus = sessionStorage.getItem(GPS_ERROR_DIALOG_STATUS);
      if (dialogStatus === '1') {
        return;
      } else {
        sessionStorage.setItem(GPS_ERROR_DIALOG_STATUS, '1');
        Dialog.alert({
          title: '获取不到您的定位',
          content: '允许“平安到家”使用您的定位，以获取当前城市和准确的订单起点',
          confirmText: '我知道了'
        });
      }
    },
    onDingweiButtonClick() {
      if (this.$refs.map) {
        if (this.incityStatus === 0) {
          this.$store
            .dispatch(GET_CURRENT_LOCATION)
            .then(() => {
              this.$refs.map.setCenterAndFitview(this.getCurrentLocation.coordinate);
            })
            .catch(reason => {
              Dialog.alert({
                title: '获取不到您的定位',
                content: '允许“平安到家”使用您的定位，以获取当前城市和准确的订单起点',
                confirmText: '我知道了'
              });
            });
        } else {
          if (this.$refs.map) {
            this.$refs.map.setFitView();
          }
        }
      }
    }
  },
  watch: {
    gpsStatus(value) {
      this.checkGpsStatus();
    },
    incityInfo(value) {
      if (!value) {
        return;
      }
      console.log('IncityInfo发生变化');
      this.$refs.map.removeFences();
      this.currentCity = value.cityName;
      if (this.incityInfo) {
        console.log('绘制围栏');
        this.$refs.map.initFences(this.incityFence);
      }
    },
    searchValue(value) {
      if (!this.autoComplete) {
        return;
      }
      this.autoComplete.search(value, (status, result) => {
        if (typeof result !== 'string') {
          if (result.tips && result.tips.length > 0) {
            let arr = [];
            result.tips.forEach((item, index) => {
              if (!item.location) {
                return;
              }
              let obj = {
                stationName: item.name,
                position: item.district + item.address,
                coordinate: [item.location.lng, item.location.lat].join(','),
                adcode: item.adcode
              };
              arr.push(obj);
            });
            this.searchList = arr;
          }
        }
      });
    }
  },
  computed: {
    ...mapGetters([
      'getCurrentLocation',
      'mqttConfig',
      'mqttClient',
      'mqttConnected',
      'currentGpsPosition',
      'gpsStatus',
      'incityStatus',
      'incityOrderStatus',
      'incityInfo',
      'incityHasTaxi',
      'incityStartPosition',
      'incityEndPosition',
      'incityFence',
      'incityFenceCenter',
      'incityDoOrderInfo',
      'incityHistoryAddress',
      'getIncityCallCarData',
      'getIncityCarpoolingNumberData',
      'getIncityOrderMoneyData',
      'getIncityCarTypeData',
      'getIncityRedMoneyData',
      'getIncityTimeData',
      'getTaxiTravelTypeData',
      'getIncityOrderDate',
      'getCallTaxiData'
    ])
  }
};
</script>

<style lang="stylus" scoped>
#incity {
  .map {
    height: calc(100vh - 170px);
  }

  .map100 {
    height: 100vh;
  }

  .top_bar {
    position: absolute;
    top: 0px;
    z-index: 1000;
    width: 100%;
  }

  .top_bar p {
    height: 88px;
    line-height: 88px;
    padding: 0px 30px;
  }

  .back_btn {
    width: 22px;
    height: 38px;
  }

  #end-searcher {
    background-color: #F8F8F8;
    font-size: 28px;
    height: 100px;
    padding-left: 30px;
    padding-right: 30px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;

    .city-name {
      min-width: 3em;
      max-width: 8em;
      color: #666;
      padding-right: 20px;
      border-right: 1px solid #E0E0E0;
      text-align: center;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
    }

    .searcher-input {
      padding-left: 20px;
      border: 0px;
      outline: none;
      background-color: transparent;
      flex: 1;
      font-size: 26px;
      height: 88px;
    }

    .searcher-btn {
      color: #888888;
      padding-left: 20px;
      font-size: 26px;
    }
  }

  .poi-list {
    width: 100vw;
    height: calc(100vh - 100px);
    background-color: #fff;
  }

  .no-result {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-top: 256px;

    .icon {
      width: 80px;
      height: 80px;
    }

    .text {
      font-size: 28px;
      color: rgba(102, 102, 102, 1);
    }
  }
}
</style>
